class Solution {
    public String toHex(int num) {
        int base = 16;
        // list 存储进制转换后的每一位
        List<Integer> list = new ArrayList<Integer>();
        long longNum;
        
        // 将负的 num 处理为补码对应的数
        if (num == 0) {
            return "0";
        } else if (num < 0) {
            longNum = 2L * Integer.MAX_VALUE + num + 2;
        } else {
            longNum = num;
        }
		// 经过上面的转化，此时正负可以统一处理
        while (longNum != 0) {
            int t = (int) (longNum % base);
            list.add(0, t);
            longNum /= base;
        }
        // 转换成字符串
        StringBuilder sb = new StringBuilder();
        for (int n : list) {
            if (n > 9) sb.append((char) (n + 'a' - 10));
            else sb.append(n);
        }
        return sb.toString();
    }
}
